package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.viewmodel;

import android.app.Activity;
import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.R;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

// 注册界面的 ViewModel
public class RegisterViewModel extends ViewModel {
    public MutableLiveData<Spinner> spinnerRoleSelect = new MutableLiveData<>();
    public MutableLiveData<EditText> edtTelephome = new MutableLiveData<>();
    public MutableLiveData<EditText> edtPassword = new MutableLiveData<>();
    public MutableLiveData<EditText> edtVertifyCode = new MutableLiveData<>();
    public MutableLiveData<Button> btnSendTelCode = new MutableLiveData<>();
    public MutableLiveData<Button> btnFinishAndRegister = new MutableLiveData<>();
    public MutableLiveData<TextView> tevReturnLogin = new MutableLiveData<>();

    private String errorMessage;
    private String verificationCode;
    private CountDownTimer countDownTimer;

    private ExecutorService executorService = Executors.newCachedThreadPool();

    public void initViews(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            spinnerRoleSelect.setValue(activity.findViewById(R.id.spin_roleSelect));
            edtTelephome.setValue(activity.findViewById(R.id.input_telephone));
            edtPassword.setValue(activity.findViewById(R.id.input_passwordRegister));
            edtVertifyCode.setValue(activity.findViewById(R.id.input_vertifyCode));
            btnSendTelCode.setValue(activity.findViewById(R.id.btn_send));
            btnFinishAndRegister.setValue(activity.findViewById(R.id.btn_register));
            tevReturnLogin.setValue(activity.findViewById(R.id.tv_returnLogon));
        }
    }

    // 异步验证注册信息
    public void validateRegistrationAsync(Context context, OnValidationResultListener listener) {
        String accountValue = edtTelephome.getValue().getText().toString();
        String passwordValue = edtPassword.getValue().getText().toString();
        String telValue = edtTelephome.getValue().getText().toString();
        String telCodeValue = edtVertifyCode.getValue().getText().toString();
        String roleValue = spinnerRoleSelect.getValue().getSelectedItem().toString().equals("家长") ? "parent" : "doctor";

        if (accountValue == null || accountValue.isEmpty()) {
            errorMessage = "手机号不能为空";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (!isValidPhoneNumber(telValue)) {
            errorMessage = "手机号格式不正确";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (passwordValue == null || passwordValue.isEmpty()) {
            errorMessage = "密码不能为空";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (passwordValue.length() < 6) {
            errorMessage = "密码长度不能少于6位";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (telCodeValue == null || telCodeValue.isEmpty()) {
            errorMessage = "验证码不能为空";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (!telCodeValue.equals(verificationCode)) {
            errorMessage = "验证码不正确";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        if (roleValue == null || roleValue.isEmpty()) {
            errorMessage = "请选择角色";
            if (listener != null) {
                listener.onValidationResult(false);
            }
            return;
        }

        /*checkPhoneNumberInDBAsync(telValue, isRegistered -> {
            if (isRegistered) {
                errorMessage = "该手机号已被注册";
                if (listener != null) {
                    listener.onValidationResult(false);
                }
            } else {
                saveUserToDBAsync(accountValue, passwordValue, accountValue, roleValue, isSaved -> {
                    if (!isSaved) {
                        errorMessage = "保存用户账户信息失败！";
                    } else {
                        errorMessage = null;
                    }
                    if (listener != null) {
                        listener.onValidationResult(isSaved);
                    }
                });
            }
        });*/
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    // 验证手机号格式
    private boolean isValidPhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        return Pattern.matches(regex, phoneNumber);
    }

    // 开始倒计时
    public void startCountdown(Context context) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        verificationCode = generateVerificationCode();
        Toast.makeText(context, "验证码是: " + verificationCode, Toast.LENGTH_LONG).show();
        btnSendTelCode.getValue().setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnSendTelCode.getValue().setText("重新发送(" + millisUntilFinished / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                btnSendTelCode.getValue().setText("发送验证码");
                btnSendTelCode.getValue().setEnabled(true);
                verificationCode = null; // 验证码失效
            }
        }.start();
    }

    // 生成随机验证码
    private String generateVerificationCode() {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append((int) (Math.random() * 10));
        }
        return code.toString();
    }

    // 添加：异步保存用户信息到数据库
    /*public void saveUserToDBAsync(String account, String password, String phoneNumber, String role, OnSaveUserListener listener) {
        // 直接调用 Firebase 保存用户，无需线程池
        new UserDao().saveUser(account, password, phoneNumber, role, new UserDao.OnSaveUserListener() {
            @Override
            public void onSaveResult(boolean isSaved) {
                if (listener != null) {
                    listener.onSaveResult(isSaved);
                }
            }
        });
    }*/

    //异步检查电话号码是否已经注册过
    /*public void checkPhoneNumberInDBAsync(String phoneNumber, OnCheckPhoneNumberListener listener) {
        // 直接调用 Firebase 方法，无需通过 executorService
        new UserDao().checkPhoneNumber(phoneNumber, new UserDao.OnCheckPhoneNumberListener() {
            @Override
            public void onCheckResult(boolean isRegistered) {
                if (listener != null) {
                    listener.onCheckResult(isRegistered);
                }
            }
        });
    }*/


    // 添加：检查手机号结果的回调接口
    public interface OnCheckPhoneNumberListener {
        void onCheckResult(boolean isRegistered);
    }

    // 添加：验证结果的回调接口
    public interface OnValidationResultListener {
        void onValidationResult(boolean isValid);
    }

    // 添加：保存用户信息结果的回调接口
    public interface OnSaveUserListener {
        void onSaveResult(boolean isSaved);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (executorService != null) {
            System.out.println("Executor service is shutting down.");
            executorService.shutdown();
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}